//
//  ICFaceManager.m
//  ICome
//
//  Created by ENN on 16/4/1.
//  Copyright © 2016年 iCom. All rights reserved.
//

#import "ICFaceManager.h"
#import "MJExtension.h"
#import "ICEmotion.h"
#import "ICFaceManager.h"
#import "UIImage+Extension.h"
#import "NSBundle+iComeSDK.h"
@implementation ICFaceManager

static NSArray * _emojiEmotions,*_custumEmotions,*gifEmotions;

+ (NSArray *)emojiEmotion
{
    if (_emojiEmotions) {
        return _emojiEmotions;
    }
    NSBundle *fileBundle = [NSBundle ic_getFileBundle];
    NSString *path = [fileBundle pathForResource:@"emoji" ofType:@"plist"];
    _emojiEmotions  = [ICEmotion mj_objectArrayWithKeyValuesArray:[NSArray arrayWithContentsOfFile:path]];
    return _emojiEmotions;
}

+ (NSArray *)customEmotion
{
    if (_custumEmotions) {
        return _custumEmotions;
    }
    NSBundle *fileBundle = [NSBundle ic_getFileBundle];
    NSString *path = [fileBundle pathForResource:@"normal_face.plist" ofType:@"plist"];
    
    _custumEmotions = [ICEmotion mj_objectArrayWithKeyValuesArray:[NSArray arrayWithContentsOfFile:path]];
    return _custumEmotions;
}

+ (NSArray *)gifEmotion
{
    return nil;
}

+ (NSMutableAttributedString *)transferMessageString:(NSString *)message
                                                font:(UIFont *)font
                                          lineHeight:(CGFloat)lineHeight
{
    NSMutableAttributedString *attributeStr
    = [[NSMutableAttributedString alloc] initWithString:message];
    if (message.length) {
        
        static NSRegularExpression *hrefRegex, *textRegex, *expression;
        static dispatch_once_t onceToken;
        dispatch_once(&onceToken, ^{
            hrefRegex = [NSRegularExpression regularExpressionWithPattern:@"(?<=href=\').+(?=\'>)" options:kNilOptions error:NULL];
            textRegex = [NSRegularExpression regularExpressionWithPattern:@"(?<=>).+(?=<)" options:kNilOptions error:NULL];
            expression = [NSRegularExpression regularExpressionWithPattern:@"\\[[a-zA-Z0-9\\/\\u4e00-\\u9fa5]+\\]" options:kNilOptions error:NULL];
        });
        
        if (!expression && !textRegex && !hrefRegex) {// 判断是否匹配成功
            return attributeStr;
        }
        
        if (expression) {
            // 对自定义表情标签进行匹配
            [attributeStr addAttribute:NSFontAttributeName value:font range:NSMakeRange(0, attributeStr.length)];
            NSArray *resultArray = [expression matchesInString:message options:0 range:NSMakeRange(0, message.length)];
            NSMutableArray *mutableArray = [NSMutableArray arrayWithCapacity:resultArray.count];
            for (NSTextCheckingResult *match in resultArray) {
                NSRange range    = match.range;
                NSString *subStr = [message substringWithRange:range];
                NSArray *faceArr = [ICFaceManager customEmotion];
                for (ICEmotion *face in faceArr) {
                    if ([face.face_name isEqualToString:subStr]) {
                        NSTextAttachment *attach   = [[NSTextAttachment alloc] init];
                        attach.image               = [UIImage imageNamedFromiComeSDKBundle:face.face_name];
                        // 位置调整Y值就行
                        attach.bounds              = CGRectMake(0, -4, lineHeight, lineHeight);
                        NSAttributedString *imgStr = [NSAttributedString attributedStringWithAttachment:attach];
                        NSMutableDictionary *imagDic   = [NSMutableDictionary dictionaryWithCapacity:2];
                        [imagDic setObject:imgStr forKey:@"image"];
                        [imagDic setObject:[NSValue valueWithRange:range] forKey:@"range"];
                        [mutableArray addObject:imagDic];
                    }
                }
            }
            for (int i =(int) mutableArray.count - 1; i >= 0; i --) {
                NSRange range;
                [mutableArray[i][@"range"] getValue:&range];
                [attributeStr replaceCharactersInRange:range withAttributedString:mutableArray[i][@"image"]];
            }
            
            
            // 对<a标签进行匹配
//            NSMutableAttributedString *linkAttributeStr
//            = attributeStr;
//            NSString *linkMessage = [attributeStr string];
//
//            if (textRegex && hrefRegex) {
//                NSTextCheckingResult *hrefResult, *textResult;
//                NSString *href = nil, *text = nil, *newText;
//                hrefResult = [hrefRegex firstMatchInString:linkMessage options:kNilOptions range:NSMakeRange(0, linkMessage.length)];
//                textResult = [textRegex firstMatchInString:linkMessage options:kNilOptions range:NSMakeRange(0, linkMessage.length)];
//
//                if (hrefResult && textResult && hrefResult.range.location != NSNotFound && textResult.range.location != NSNotFound) {
//                    href = [linkMessage substringWithRange:hrefResult.range];
//                    text = [linkMessage substringWithRange:textResult.range];
//
//                    newText = [linkMessage stringByReplacingCharactersInRange:NSMakeRange((hrefResult.range.location - 9), textResult.range.location+textResult.range.length - (hrefResult.range.location - 9) + 4) withString:text];
//                }
//
//                if (href.length && text.length && newText.length) {
//                    [linkAttributeStr setAttributes:@{NSForegroundColorAttributeName : DARKBLUECOLOR,NSFontAttributeName : [UIFont systemFontOfSize:15], NSLinkAttributeName :href} range:[newText rangeOfString:text]];
//                }
//                return linkAttributeStr;
//            }
            return attributeStr;
        }
    }
    
    return attributeStr;
}


+ (BOOL)isContainsEmoji:(NSString *)string {
    __block BOOL isEomji = NO;
    [string enumerateSubstringsInRange:NSMakeRange(0, [string length])options:NSStringEnumerationByComposedCharacterSequences usingBlock:
     ^(NSString *substring,NSRange substringRange,NSRange enclosingRange,BOOL *stop) {
         const unichar hs = [substring characterAtIndex:0];
         if (0xd800 <= hs && hs <=0xdbff) {
             if (substring.length >1) {
                 const unichar ls = [substring characterAtIndex:1];
                 const int uc = ((hs -0xd800) *0x400) + (ls -0xdc00) +0x10000;
                 if (0x1d000 <= uc && uc <=0x1f77f) {
                     isEomji =YES;
                 }
             }
         } else if (substring.length >1) {
             const unichar ls = [substring characterAtIndex:1];
             if (ls ==0x20e3) {
                 isEomji =YES;
             }
         } else {
             if (0x2100 <= hs && hs <=0x27ff && hs !=0x263b) {
                 isEomji =YES;
             } else if (0x2B05 <= hs && hs <=0x2b07) {
                 isEomji =YES;
             } else if (0x2934 <= hs && hs <=0x2935) {
                 isEomji =YES;
             } else if (0x3297 <= hs && hs <=0x3299) {
                 isEomji =YES;
             } else if (hs ==0xa9 || hs ==0xae || hs ==0x303d || hs ==0x3030 || hs ==0x2b55 || hs ==0x2b1c || hs ==0x2b1b || hs ==0x2b50|| hs ==0x231a ) {
                 isEomji =YES;
             }
         }
     }];
    return isEomji;
}

@end
